package com.bestcem.xm.common.core.sql;

import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.common.core.constant.Constants;
import com.bestcem.xm.common.core.constant.ErrorCodes;
import org.springframework.util.CollectionUtils;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;

public abstract class ConditionTraverser {

    public void traverse(JSONObject condition) {
        this.traverse(condition, null);
    }

    public void traverse(JSONObject condition, Map<String, Object> contextParams) {
        Queue<JSONObject> queue = new LinkedList<>();
        queue.offer(condition);

        JSONObject currentCondition;
        while ((currentCondition = queue.poll()) != null) {
            List<JSONObject> filters = (List<JSONObject>) currentCondition.get(ConditionConstant.FILTERS);
            if (filters != null) {
                if (CollectionUtils.isEmpty(filters)) {
                    throw new ConditionException("condition.filters missing");
                }

                // 自动打标签条件，每个条件组最多包含5个条件或条件组
                if (filters.size() > Constants.MAX_SIBLING_CONDITION_NUM) {
                    throw new ConditionException(ErrorCodes.A0400, "每个条件组最多包含5个条件或条件组");
                }

                filters.forEach(queue::offer);
                this.onCompoundCondition(currentCondition, contextParams);
            } else {
                this.onSimpleCondition(currentCondition, contextParams);
            }
        }
    }

    protected void onCompoundCondition(JSONObject condition, Map<String, Object> contextParams) {}

    protected void onSimpleCondition(JSONObject condition, Map<String, Object> contextParams) {}
}
